/* eslint-disable no-param-reassign */
import Toast from 'tdesign-miniprogram/toast/index';
// 接口
import { fetchShopSearchList, fetchShopAddcart } from '~/request/api';

const initFilters = {
  overall: 1,
  orderby_price: '',
  orderby_stock: '',
};

Page({
  data: {
    goodsList: [],
    orderby_price: '',
    orderby_stock: '',
    overall: 1,
    filter: initFilters,
    hasLoaded: false,
    keywords: '',
    loadMoreStatus: 0,
    loading: true,
  },

  total: 0,
  page: 1,
  page_size: 30,

  onLoad(options) {
    const { searchValue = '', type_id } = options || {};
    this.setData(
      {
        keywords: searchValue,
        type_id,
      },
      () => {
        this.init(true);
      },
    );
  },

  generalQueryData(reset = false) {
    const { filter, keywords, type_id } = this.data;
    const { page, page_size } = this;
    const { orderby_price, orderby_stock, overall } = filter;
    const params = {
      orderby_price,
      orderby_stock,
      page,
      page_size,
      search: keywords,
      type_id
    };

    if (overall) {
      params.orderby_price = undefined;
      params.orderby_stock = undefined;
    }
    if (reset) return params;
    return {
      ...params,
      page: page + 1,
      page_size,
    };
  },

  async init(reset = true) {
    const { loadMoreStatus, goodsList = [] } = this.data;
    const params = this.generalQueryData(reset);
    if (loadMoreStatus !== 0) return;
    this.setData({
      loadMoreStatus: 1,
      loading: true,
    });
    try {
      const result = await fetchShopSearchList(params);
      const { data: spuList, total: totalCount = 0 } = result;
      if (totalCount === 0 && reset) {
        this.total = totalCount;
        this.setData({
          emptyInfo: {
            tip: '抱歉，未找到相关商品',
          },
          hasLoaded: true,
          loadMoreStatus: 0,
          loading: false,
          goodsList: [],
        });
        return;
      }

      const _goodsList = reset ? spuList : goodsList.concat(spuList);
      _goodsList.forEach((v) => {
        v.hideKey = { desc: true };
      });
      const _loadMoreStatus = _goodsList.length === totalCount ? 2 : 0;
      this.page = params.page || 1;
      this.total = totalCount;
      this.setData({
        goodsList: _goodsList,
        loadMoreStatus: _loadMoreStatus,
      });
    } catch (error) {
      this.setData({
        loading: false,
      });
    }
    this.setData({
      hasLoaded: true,
      loading: false,
    });
  },

  handleSubmit(e) {
    const { value } = e.detail;
    this.setData(
      {
        goodsList: [],
        keywords: value,
        loadMoreStatus: 0,
      },
      () => {
        this.init(true);
      },
    );
  },

  onReachBottom() {
    const { goodsList } = this.data;
    const { total = 0 } = this;
    if (goodsList.length === total) {
      this.setData({
        loadMoreStatus: 2,
      });
      return;
    }
    this.init(false);
  },

  // 添加购物车
  async shopAddcart(params) {
    try {
      const res = await fetchShopAddcart(params);
      Toast({
        context: this,
        selector: '#t-toast',
        message: res.msg,
        icon: '',
        duration: 1000,
      });
    } catch (error) {
      console.log(error);
    }
  },

  handleAddCart(e) {
    const { goods } = e.detail;
    this.shopAddcart({ goods_id: goods.id, num: 1 });
  },

  gotoGoodsDetail(e) {
    const { goods } = e.detail;
    wx.navigateTo({
      url: `/pages/goods/details/index?goods_id=${goods.id}`,
    });
  },

  handleFilterChange(e) {
    console.log(e.detail);
    const { overall, orderby_price, orderby_stock } = e.detail;
    const { total } = this;
    const _filter = {
      orderby_price,
      orderby_stock,
      overall,
    };
    this.setData({
      filter: _filter,
      orderby_price,
      orderby_stock,
      overall,
    });

    this.page = 1;
    this.setData(
      {
        goodsList: [],
        loadMoreStatus: 0,
      },
      () => {
        total && this.init(true);
      },
    );
  },
});
